using System;
using System.Web;
using System.Web.Security;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;

namespace CKS.FormsBasedAuthentication
{
    /// <summary>
    /// Custom save button to make sure the email address gets saved back to the membership provider
    /// </summary>
    public class FBASaveButton : SaveButton
    {
        SPListItem _item = null;
 
        protected override string DefaultTemplateName
        {
            get { return "FBASaveButton"; }
        }
        
        protected override bool SaveItem()
        {
            bool saved = base.SaveItem();

            if (saved)
            {
                // only save the email if the right list and the FBASaveAction feature enabled.
                _item = base.ItemContext.Item as SPListItem;
                if ((_item.ParentList.Title == SPUtility.GetLocalizedString("$Resources:userinfo_schema_listtitle", "core", Web.Language)) &&
                    (Utils.IsWebAppFBAEnabled(this.Web.Site)) &&
                    (this.MySettingsFeatureEnabled()))
                {
                    SaveFBAEmail();
                    SPUtility.Redirect(Page.Request.QueryString["Source"], SPRedirectFlags.Default, HttpContext.Current, "");
                }

            }

            return saved;            
        }

        private bool MySettingsFeatureEnabled()
        {
            // check if the FBASaveAction feature is enabled on the current site
            foreach (SPFeature feature in base.Web.Site.Features)
            {
                SPFeatureDefinition definition = feature.Definition;
                if (definition != null && definition.DisplayName == "FBASaveAction")
                {
                    return true;
                }
            }
            return false;
        }

        private void SaveFBAEmail()
        {
            // get updated user details            
            string userName = _item.GetFormattedValue("Name");
            string email = _item.GetFormattedValue("EMail");

            try
            {
                // get fba user
                string provider = Utils.GetMembershipProvider(this.Web.Site).ToLower();
                MembershipUser user = Membership.GetUser(userName.Replace(provider + ":", ""));

                // update fba user
                user.Email = email;
                Membership.UpdateUser(user);

                // send user back to site root (not to people & groups)
                this.RedirectUrl = Web.Url;
            }
            catch (Exception ex)
            {
                Utils.LogError(ex, true);
            }
        }
    }
}